//
// Created by WenDaoJiang on 2017/11/20.
// Copyright (c) 2017 文道江. All rights reserved.
//

#import "HybridIDCardAction.h"

@implementation HybridIDCardAction {

}

- (void)scan:(id)params {
    NSLog(@"扫描身份证 %@", params);

    // 读取配置信息
    NSDictionary *BaiduOrcConfig = [[HybridBridge defaultHybridBridge] appInfo][@"BaiduOrc"];

    [[AipOcrService shardService] authWithAK:BaiduOrcConfig[@"AK"] andSK:BaiduOrcConfig[@"SK"]];
    UIViewController * vc = [AipCaptureCardVC ViewControllerWithCardType:[params[@"front"] boolValue] ? CardTypeLocalIdCardFont : CardTypeLocalIdCardBack andDelegate:self];
    [self.controller presentViewController:vc animated:YES completion:nil];
}

#pragma mark delegate

- (void)ocrOnIdCardSuccessful:(id)result {

    NSDictionary *dic = result[@"result"][@"words_result"];
    NSMutableDictionary *idCardInfo = [[NSMutableDictionary alloc] initWithDictionary:@{
            @"path": result[@"path"],
            @"url": [@"file://" stringByAppendingString: result[@"path"]]
    }];
    [dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@", [NSString stringWithFormat:@"%@: %@\n", key, obj[@"words"]]);
        if([@"姓名" isEqualToString:key]){
            idCardInfo[@"name"] = obj[@"words"];
        }else if([@"性别" isEqualToString:key]){
            idCardInfo[@"gender"] = obj[@"words"];
        }else if([@"出生" isEqualToString:key]){
            idCardInfo[@"birthday"] = obj[@"words"];
        }else if([@"公民身份号码" isEqualToString:key]){
            idCardInfo[@"idNumber"] = obj[@"words"];
            idCardInfo[@"idCardSide"] = @"front";
        }else if([@"住址" isEqualToString:key]){
            idCardInfo[@"address"] = obj[@"words"];
        }else if([@"民族" isEqualToString:key]){
            idCardInfo[@"ethnic"] = obj[@"words"];
        }else if([@"失效日期" isEqualToString:key]){
            idCardInfo[@"expiryDate"] = obj[@"words"];
            idCardInfo[@"idCardSide"] = @"back";
        }else if([@"签发日期" isEqualToString:key]){
            idCardInfo[@"signDate"] = obj[@"words"];
        }else if([@"签发机关" isEqualToString:key]){
            idCardInfo[@"issueAuthority"] = obj[@"words"];
        }
    }];
    [self callback:YES data:idCardInfo];
}

- (void)ocrOnGeneralSuccessful:(id)result {
    NSLog(@"ocrOnGeneralSuccessful");
}

- (void)ocrOnDrivingLicenseSuccessful:(id)result {
    NSLog(@"ocrOnDrivingLicenseSuccessful");
}

- (void)ocrOnPlateLicenseSuccessful:(id)result {
    NSLog(@"ocrOnPlateLicenseSuccessful");
}

- (void)ocrOnVehicleLicenseSuccessful:(id)result {
    NSLog(@"ocrOnVehicleLicenseSuccessful");
}

- (void)ocrOnFail:(NSError *)error {
    [self callback:NO data:error.domain];
}

@end